<template>
    <van-nav-bar
    title="地址"
    left-text="返回"
    left-arrow
    @click-left="onClickLeft"
    />

    <van-address-list 
        v-model="active"
        :list="list"
        default-tag-text="默认"
        @add="AddressAdd"
        @edit="AddressEdit"
    />
</template>

<script setup>
    import { watch } from "vue";

    const {proxy} = getCurrentInstance()

    let active = ref(0)
    //收获地址列表
    let list = ref([])
    const action = ref(proxy.$route.query.action)
    onBeforeMount(async()=>{
        (await proxy.$GET({
            url:'/business/address'
        })).forEach(e => {
            list.value.push({
                id: e.id,
                name: e.consignee,
                tel: e.mobile,
                address: e.province_text+e.city_text+e.district_text+e.address,
                isDefault: e.status==1
            })
            e.status==1 && (active.value = e.id)
        });
        if(action.value=='select'&&proxy.$route.query.addressid){
            active.value = Number(proxy.$route.query.addressid)
        }
        watch(active,async(newValue)=>{
            if(action.value=='select'){
                proxy.$router.push({path:'/cart/confirm',query:{addressid:active.value}})
                return
            }
            list.value.forEach(e=>{
                e.isDefault=(e.id==newValue)
            })
            const result = await proxy.$PUT({
                url:'/business/address',
                params:{id:newValue},
            })
            if(result.code==1){
                showSuccessToast({
                    message: result.msg,
                    duration: 1000,
                    onClose: () => proxy.$router.push('/address')
                })
            }else{
                showFailToast({
                    message: result.msg,
                    duration: 1000,
                })
            }
        })
    })
    
    //收获地址添加
    const AddressAdd = async () => {
        if(action.value=='select'){
            proxy.$router.push({path:'/address/add',query:{action: 'select',addressid:active.value}})
        }else{
            proxy.$router.push('/address/add')
        }
    }
    //收获地址的编辑
    const AddressEdit = async (item) => {
        if(action.value=='select'){
            proxy.$router.push({path:'/address/edit' , query: {id:item.id,action: 'select',addressid:active.value}})
        }else{
            proxy.$router.push({path:'/address/edit' , query: {id:item.id}})
        }
    }
    const onClickLeft = ()=>{
        if(action.value=='select')
        {
            proxy.$router.push({path:'/cart/confirm',query:{addressid:active.value}})
        }else{
            proxy.$router.push('/business')
        }
    }
</script>